package com.sumer.psychology.blog.infrastructure.persistence.hibernate;

import com.sumer.psychology.blog.domain.model.Category;
import com.sumer.psychology.blog.domain.model.CategoryId;
import com.sumer.psychology.blog.domain.model.CategoryRepository;
import com.sumer.psychology.common.domain.model.Availability;
import com.sumer.psychology.common.persistence.hibernate.AbstractHibernateRepository;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import java.util.UUID;

/**
 * 目录资源库
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/3
 * Time: 9:16
 */
public class HibernateCategoryRepository extends AbstractHibernateRepository implements CategoryRepository {
    @Override
    public CategoryId nextIdentity() {
        return new CategoryId(UUID.randomUUID().toString());
    }

    @Override
    public void add(Category aCategory) {
        session().saveOrUpdate(aCategory);
    }

    @Override
    public Category activeCategoryOfId(CategoryId categoryId) {
        return category(categoryId, true);
    }

    @Override
    public Category categoryOfId(CategoryId categoryId) {
        return category(categoryId, false);
    }

    private Category category(CategoryId categoryId, boolean active) {
        Criteria criteria = session()
                .createCriteria(Category.class)
                .add(Restrictions.eq("categoryId", categoryId));
        if (active) {
            criteria.add(Restrictions.eq("availability", Availability.ACTIVE));
        }
        return (Category) criteria.uniqueResult();
    }
}
